/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.mem.impl;

import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;

import org.sabayframework.mem.Memorizable;
import org.sabayframework.queue.ExecutionQueue;

/**
 * Transaction on temporary memory space.
 * */
public class HeapTransaction extends TransactionImpl {

	
	final static class RequestActivity extends TxActivity {
		
		private final Long2ObjectOpenHashMap<Memorizable> records;		
		
		RequestActivity(TransactionImpl transaction, AbstractSpace tm) {
			super(transaction, tm);
			this.records = new Long2ObjectOpenHashMap<Memorizable>();
		}
		
		@Override
		protected Boolean[] contains(long[] ids) throws Exception {
			Boolean[] res = new Boolean[ids.length];
			for(int i=0;i<ids.length;++i) {
				res[i] = records.containsKey(ids[i]);
			}
			return res;
		}

		@Override
		protected Memorizable[] read(Class<? extends Memorizable> objectClass, long[] ids) throws Exception {
			Memorizable[] res= new Memorizable[ids.length];
			for(int i=0;i<ids.length;++i) {
				res[i] = records.get(ids[i]);
				if(res[i] == null){
					res[i] = objectClass.newInstance();
					res[i].setId(ids[i]);
				}
			}
			return res;
		}


		@Override
		protected boolean write(Memorizable[] ms) throws Exception {
			for(Memorizable m : ms) records.put(m.getId(), m);
			return true;
		}


		@Override
		protected boolean delete(long[] ids) throws Exception {
			for(int i=0;i<ids.length;++i) records.remove(ids[i]);
			return true;
		}

		@Override
		protected boolean complete(Status status) {
			records.clear();
			return true;
		}

	}
	public HeapTransaction(long id, ExecutionQueue executionQueue,AbstractSpace tm) {
		super(id, executionQueue);
		submitProcessingActivity( new RequestActivity(this, tm));
	}

}
